package com.lalosoft.gastostarjetaweb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.annotations.Transactional;

import com.lalosoft.gastostarjetaweb.model.Item;
import com.lalosoft.gastostarjetaweb.pmf.PMF;

public class ItemDao {
	
	public static Long save(Item item){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Item itemSaved = null;
		try{
			itemSaved = pm.makePersistent(item);
		} finally {
			pm.close();
		}
		return itemSaved.getId();
	}
	
	public static void deleteById(Long id, PersistenceManager pm){
		Query q = pm.newQuery(Item.class);
		List<Item> list =  (List<Item>)q.execute();
		if(list.size() > 0){
			boolean encontrado = false;
			int i = 0;
			while(!encontrado && i < list.size()){
				Item temp = list.get(i);
				if(temp.getId().equals(id)){
					encontrado = true;
					pm.deletePersistent(temp);
				}
				i++;
			}
		}
	}
	
	@Transactional
	public static List<Item> findAll(PersistenceManager pm){
		List<Item> list = new ArrayList<Item>();
		Query q = pm.newQuery(Item.class);
		list = (List<Item>)q.execute();
		return list;
	}
	
	public static List<Item> findByToken(String token, PersistenceManager pm){
		List<Item> list = new ArrayList<Item>();
		Query q = pm.newQuery(Item.class);
		List<Item> items = (List<Item>)q.execute();
		if(items.size() > 0){
			for(Item temp : items){
				if(temp.getUserUuid().equals(token)){
					list.add(temp);
				}
			}
		}
		return list;
	}
	
	public static void update(Item item, PersistenceManager pm){
		pm.makePersistent(item);
		
	}
}
